package com.vueblog.service.impl;

import com.vueblog.dao.BlogDao;
import com.vueblog.po.Blog;
import com.vueblog.service.BlogService;
import com.vueblog.util.MarkdownUtils;
import com.vueblog.vo.Archives;
import com.vueblog.vo.DetailBlog;
import com.vueblog.vo.SimpleBlog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogDao blogDao;

    @Override
    public List<SimpleBlog> findByTitleAndTypeIdAndPublished(Blog blog) {
        String blogTitle = "%"+blog.getTitle()+"%";
        blog.setTitle(blogTitle);
        return blogDao.findByTitleAndTitleAndPublished(blog);
    }

    @Override
    @Transactional
    public int saveBlog(Blog blog) {
        blog.setCommentCount(0);
        blog.setViews(0);
        blog.setUpdateTime(new Date());
        blog.setCreateTime(new Date());
        return blogDao.saveBlog(blog);
    }

    @Override
    public DetailBlog findDetailBlogById(int id) {
        return blogDao.findDetailBlogById(id);
    }

    @Override
    @Transactional
    public int updateBlog(Blog blog) {
        return blogDao.updateBlog(blog);
    }

    @Override
    @Transactional
    public int deleteBlog(int id) {
        return blogDao.deleteBlog(id);
    }

    @Override
    public List<DetailBlog> findAllForIndex() {
        return blogDao.findAllForIndex();
    }

    @Override
    @Transactional
    public DetailBlog findShowBlogById(int id) {
        DetailBlog blog = blogDao.findShowBlogById(id);
        if(blog == null){
            return null;
        }
        String content = blog.getContent();
        content = MarkdownUtils.markdownToHtmlExtensions(content);
        blog.setContent(content);
        //更新view
        blogDao.updateView(id);
        return blog;
    }

    @Override
    public List<DetailBlog> findShowBlogsByTypeId(int typeId) {
        return blogDao.findShowBlogsByTypeId(typeId);
    }

    @Override
    public List<Archives> archiveShowBlog() {
        List<String> years = blogDao.findGroupYear();
        List<Archives> archives = new ArrayList<>();
        for (String year : years) {
            Archives archive = new Archives();
            archive.setYear(Integer.parseInt(year));
            archive.setBlogs(blogDao.findShowBlogByYear(year));
            archives.add(archive);
        }
        return archives;
    }

    @Override
    public int countShowBlog() {
        return blogDao.countShowBlog();
    }

    @Override
    public List<DetailBlog> findShowBlogByTitleOrContent(String keyword) {
        return blogDao.findShowBlogByTitleOrContent("%"+keyword+"%");
    }
}
